import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import '../style/About.css';
import { zhu } from "../utlis/https";

function About() {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
    });
    const [errors, setErrors] = useState({});
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);
    const [showSuccessModal, setShowSuccessModal] = useState(false);
    const [showUsernameDuplicateModal, setShowUsernameDuplicateModal] = useState(false); // 用户名重复模态框状态

    // 当注册成功模态框显示时，设置定时器自动跳转到登录页面
    useEffect(() => {
        if (showSuccessModal) {
            const timer = setTimeout(() => {
                navigate('/home'); // 3秒后自动跳转到登录页面
            }, 3000);

            return () => clearTimeout(timer); // 清理定时器
        }
    }, [showSuccessModal, navigate]);

    // 处理输入变化
    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [name]: value,
        }));
        // 清除对应字段的错误
        if (errors[name]) {
            setErrors((prevErrors) => ({
                ...prevErrors,
                [name]: '',
            }));
        }
    };

    // 验证表单
    const validateForm = () => {
        const newErrors = {};

        // 用户名验证
        if (!formData.username.trim()) {
            newErrors.username = '请输入用户名';
        } else if (formData.username.length < 3) {
            newErrors.username = '用户名长度不能少于3位';
        } else if (formData.username.length > 20) {
            newErrors.username = '用户名长度不能超过20位';
        }

        // 密码验证
        if (!formData.password) {
            newErrors.password = '请输入密码';
        } else if (formData.password.length < 6) {
            newErrors.password = '密码长度不能少于6位';
        } else if (formData.password.length > 20) {
            newErrors.password = '密码长度不能超过20位';
        }

        // 确认密码验证
        if (!formData.confirmPassword) {
            newErrors.confirmPassword = '请确认密码';
        } else if (formData.confirmPassword !== formData.password) {
            newErrors.confirmPassword = '两次输入的密码不一致';
        }

        // 邮箱验证
        if (!formData.email.trim()) {
            newErrors.email = '请输入邮箱';
        } else {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(formData.email)) {
                newErrors.email = '请输入有效的邮箱地址';
            }
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    // 处理表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();

        if (validateForm()) {
            setIsSubmitting(true);

            try {
                const res = await zhu({
                    name: formData.username,
                    pwd: formData.password,
                    emails: formData.email,
                });
                console.log(res);

                setIsSubmitting(false);

                // 处理不同的响应情况
                if (res.code === 3) {
                    // 用户名重复，显示美观的弹出框
                    setShowUsernameDuplicateModal(true);
                } else if (res.code === 0 || res.code === 1) {
                    // 注册成功，显示成功提示并准备跳转
                    setShowSuccessModal(true);
                } else {
                    // 其他错误情况
                    alert('注册失败，请稍后重试');
                }
            } catch (err) {
                console.error('注册请求失败:', err);
                setIsSubmitting(false);
                alert('网络错误，请稍后重试');
            }
        }
    };

    // 关闭用户名重复模态框
    const closeUsernameDuplicateModal = () => {
        setShowUsernameDuplicateModal(false);
    };

    // 切换密码可见性
    const togglePasswordVisibility = () => {
        setShowPassword(!showPassword);
    };

    // 切换确认密码可见性
    const toggleConfirmPasswordVisibility = () => {
        setShowConfirmPassword(!showConfirmPassword);
    };

    return (
        <div className="register-container">
            <div className="register-box">
                <h2 className="register-title">创建账号</h2>
                <form onSubmit={handleSubmit} className="register-form">
                    <div className="form-group">
                        <label htmlFor="username">用户名</label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            value={formData.username}
                            onChange={handleChange}
                            placeholder="请输入3-20位用户名"
                            className={errors.username ? 'error' : ''}
                            maxLength={20}
                            autoComplete="username"
                        />
                        {errors.username && <span className="error-message">{errors.username}</span>}
                    </div>

                    <div className="form-group">
                        <label htmlFor="email">邮箱</label>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            value={formData.email}
                            onChange={handleChange}
                            placeholder="请输入有效的邮箱地址"
                            className={errors.email ? 'error' : ''}
                            autoComplete="email"
                        />
                        {errors.email && <span className="error-message">{errors.email}</span>}
                    </div>

                    <div className="form-group">
                        <label htmlFor="password">密码</label>
                        <div className="password-container">
                            <input
                                type={showPassword ? "text" : "password"}
                                id="password"
                                name="password"
                                value={formData.password}
                                onChange={handleChange}
                                placeholder="请输入6-20位密码"
                                className={errors.password ? 'error' : ''}
                                maxLength={20}
                                autoComplete="new-password"
                            />
                            <button
                                type="button"
                                className="toggle-password"
                                onClick={togglePasswordVisibility}
                                title={showPassword ? "隐藏密码" : "显示密码"}
                                aria-label={showPassword ? "隐藏密码" : "显示密码"}
                            >
                                {showPassword ? '👁️‍🗨️' : '👁️'}
                            </button>
                        </div>
                        {errors.password && <span className="error-message">{errors.password}</span>}
                    </div>

                    <div className="form-group">
                        <label htmlFor="confirmPassword">确认密码</label>
                        <div className="password-container">
                            <input
                                type={showConfirmPassword ? "text" : "password"}
                                id="confirmPassword"
                                name="confirmPassword"
                                value={formData.confirmPassword}
                                onChange={handleChange}
                                placeholder="请再次输入密码"
                                className={errors.confirmPassword ? 'error' : ''}
                                maxLength={20}
                                autoComplete="new-password"
                            />
                            <button
                                type="button"
                                className="toggle-password"
                                onClick={toggleConfirmPasswordVisibility}
                                title={showConfirmPassword ? "隐藏密码" : "显示密码"}
                                aria-label={showConfirmPassword ? "隐藏密码" : "显示密码"}
                            >
                                {showConfirmPassword ? '👁️‍🗨️' : '👁️'}
                            </button>
                        </div>
                        {errors.confirmPassword && <span className="error-message">{errors.confirmPassword}</span>}
                    </div>

                    <button
                        type="submit"
                        className="register-button"
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? (
                            <>
                                <span className="loading-spinner"></span>
                                注册中...
                            </>
                        ) : '注册'}
                    </button>

                    <div className="login-link">
                        <span>已有账号？</span>
                        <button
                            type="button"
                            className="to-login-btn"
                            onClick={() => navigate('/home')}
                        >
                            立即登录
                        </button>
                    </div>
                </form>
            </div>

            {/* 注册成功模态框 */}
            {showSuccessModal && (
                <div className="success-modal-overlay">
                    <div className="success-modal">
                        <div className="success-icon">✓</div>
                        <h3 className="success-title">注册成功！</h3>
                        <p className="success-message">您的账号已创建成功，即将跳转到登录页面...</p>
                        <div className="success-progress-bar">
                            <div className="success-progress"></div>
                        </div>
                    </div>
                </div>
            )}

            {/* 用户名重复模态框 */}
            {showUsernameDuplicateModal && (
                <div className="error-modal-overlay">
                    <div className="error-modal">
                        <div className="error-icon">⚠️</div>
                        <h3 className="error-title">用户名已存在</h3>
                        <p className="error-message">该用户名已被使用，请选择其他用户名重试。</p>
                        <button
                            className="error-close-btn"
                            onClick={closeUsernameDuplicateModal}
                        >
                            确定
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}

export default About;